/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.common.template.helper;

import com.apache.portal.common.oscache.BaseOsCache;
import com.apache.portal.common.oscache.OsCacheOtherManager;
import com.apache.portal.common.template.FreemarkerHelper;
import com.apache.portal.common.util.FileOperate;
import com.apache.portal.thread.CreateParamManagerInfoJob;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * description:  生成页面实现类
 *
 * @author dyhou 创建时间：2016
 */
public class PagesTempManager extends SupperTemplateManager {

    public boolean createPage(Map<String, Object> param) {
        return newMethod(param);
    }

    private boolean newMethod(Map<String, Object> param) {
        boolean mark = false;
        Map<String, String> temp = (Map) param.get("template");

        String root = ToolsUtil.getInstance().getLocalByKey("config.properties","jsp_path");//路径根目录
        if (!root.endsWith("/"))
            root += "/";
        String xmlPath = root + String.valueOf(temp.get("codeUrl")) + "/";//生成地址
        String projectName = String.valueOf(temp.get("projectName"));//工程名
        Map<String, Object> data = new HashMap<String, Object>();
        String infoTableName = String.valueOf(temp.get("mainObj"));//主体对象 ,如：trpTest
        List<Map> sortInfoList = null;
        if (StrUtil.isNotNull(infoTableName)) {
            infoTableName = upperCharToUnderLine(infoTableName, false);//转化成trp_test
            //查询pub_sort_info，得到主体对象的表定义
            Map<String, Object> sortInfoParamVo = new HashMap<String, Object>();
            sortInfoParamVo.put("sortInfo.w_infoTableName", infoTableName);
            sortInfoParamVo.put("modelTypes", "s_sortInfo");
            sortInfoList = (List) init(sortInfoParamVo);//获取数据集定义信息（目前为一条数据）
            if (ToolsUtil.isEmpty(sortInfoList)) {
                log.info(infoTableName + "表没有获取到数据表信息");
                return mark;
            }
        } else {
            temp.put("main_obj", "");
            temp.put("main_id", "");
        }
        if (StrUtil.isNull(String.valueOf(temp.get("titleName")))) {
            temp.put("title_name", "");
        }
        if (StrUtil.isNull(String.valueOf(temp.get("portName")))) {
            temp.put("port_name", "");
        }
        if (StrUtil.isNull(String.valueOf(temp.get("formSearch")))) {
            temp.put("form_search", "");
            temp.put("form_del", "");
        }
        if (StrUtil.isNull(String.valueOf(temp.get("ifSingle")))) {
            temp.put("if_single", "F");
        }
        if (StrUtil.isNull(String.valueOf(temp.get("menuId")))) {
            temp.put("menu_id", "");
        }

        String sortCode = "";
        String objName = "";
        String primaryKeyId = "";
        String dataPrimaryKey = "";
        if (null != sortInfoList) {
            for (Map map : sortInfoList) {
                sortCode = String.valueOf(map.get("sortId"));//分类代号
                objName = String.valueOf(map.get("objName"));//实体名（如：trpPro)
            }
            //查询pub_metadata，得到该表的字段属性。
            Map<String, Object> metadataParamVo = new HashMap<String, Object>();
            metadataParamVo.put("metadata.w_sortId", sortCode);
            metadataParamVo.put("modelTypes", "s_metadata");
            metadataParamVo.put("orderBy", "metadata.reserved1");
            List<Map> metadataList = (List) init(metadataParamVo);

            for (Map map : metadataList) {
                if ("1".equals(String.valueOf(map.get("dataRestrict")))) {//获取主键属性
                    primaryKeyId = String.valueOf(map.get("dataAttr"));
                    dataPrimaryKey = String.valueOf(map.get("dataAttr"));
                }
            }

            data.put("sort", sortInfoList.get(0));
            data.put("objName", objName);///ke'f
            data.put("primaryKeyId", primaryKeyId);
            data.put("dataPrimaryKey", dataPrimaryKey);

            data.put("metadatas", metadataList);//表字段属性定义信息
        } else {
            data.put("sort", null);
            data.put("objName", StrUtil.doNull(objName, String.valueOf(temp.get("mainObj"))));
            data.put("primaryKeyId",
                    StrUtil.doNull(primaryKeyId, String.valueOf(temp.get("mainId"))));
            data.put("dataPrimaryKey", dataPrimaryKey);
        }

        try {
            data.put("projectName", projectName);
            FileOperate.getInstance().newCreateFolder(xmlPath);//生成路径
            Map<String, Object> mtData = new HashMap<String, Object>();
            Map<String, Object> bns = new HashMap<String, Object>();
            Map<String, Object> objNameAllMap = new HashMap<String, Object>();
            List<Map> listDetial = (List) param.get("detail");//模板详细列表
            data.put("detailList", listDetial);
            if (null != listDetial) {
                for (int i = 0; i < listDetial.size(); i++) {
                    Map detail = listDetial.get(i);
                    String objNames = String.valueOf(detail.get("objName"));//实体名（操作几张表）
                    String str[] = objNames.split(",");
                    String modelTypesNo[] = new String[3];//定义规则参数数组
                    modelTypesNo[0] = "i_" + str[0];//插入
                    modelTypesNo[1] = "u_" + str[0];//修改
                    modelTypesNo[2] = "s_" + str[0];//查询
                    data.put("size_" + detail.get("tabNo").toString(), str.length);//tab数量
                    List<String> oNames = new ArrayList<String>();//tab ID信息
                    String bkey = "objName_" + detail.get("tabNo").toString();//页签集合MAP标识
                    for (int j = 0; j < str.length; j++) {
                        String sortId = this.upperCharToUnderLine(str[j]);
                        if (StrUtil.isNull(sortId))
                            continue;
                        Map<String, Object> paramVo = new HashMap<String, Object>();
                        paramVo.put("metadata.w_sortId", sortId);
                        paramVo.put("modelTypes", "s_metadata");
                        paramVo.put("orderBy", "metadata.reserved1");
                        List<Map> mts = (List) init(paramVo);
                        oNames.add(str[j]);
                        objNameAllMap.put(str[j], mts);
                        mtData.put("metadata_" + str[j] + detail.get("tabNo").toString(), mts);
                        if (j > 0) {
                            modelTypesNo[0] += ",i_" + str[j];
                            modelTypesNo[1] += ",u_" + str[j];
                            modelTypesNo[2] += ",s_" + str[j];
                        }
                    }
                    bns.put(bkey, oNames);
                    //				data.put("mts", mtData);
                    //				String templateDefaultName = String.valueOf(temp.get("templateUrl")) + "/"
                    //						+ String.valueOf(temp.get("templateName"));
                    String pageName = String.valueOf(temp.get("pageName"));
                    //				String result = FreemarkerHelper.instance().getTemplateStr(templateDefaultName, data);
                    //				result = result.replace("###", "$");
                    //				FileOperate.getInstance().newCreateFile(xmlPath + pageName, result);

                    //往paramManager表中插入相关配置。
                    String modelTypes[] = { modelTypesNo[0], modelTypesNo[1], modelTypesNo[2] };
                    String FormNames[] = { "addForm" + detail.get("tabNo"),
                            "editForm" + detail.get("tabNo"), "searchForm" + detail.get("tabNo") };
                    //buildTemplateManager(pageName,modelTypes,FormNames);
                }
            }
            data.put("metadataList", mtData);
            data.put("objNameMap", bns);
            data.put("objNameAllMap", objNameAllMap);
            String templateRoot = temp.get("templateUrl");
            templateRoot+=templateRoot.endsWith("/")?"":"/";
            String templateDefaultName = templateRoot + temp.get("templateName");
            String pageName = String.valueOf(temp.get("pageName"));
            data.put("template", temp);
//            String result = FreemarkerHelper.instance().getTemplateStr(data, templateDefaultName);
            String result = FreemarkerHelper.instance().getTemplateResourcesStr(data, templateDefaultName);
            result = result.replace("###", "$");
            FileOperate.getInstance().newCreateFile(xmlPath + pageName, result);
            mark = true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成页面失败", e);
        }
        return mark;
    }

    /**
     * description:  生成IUS参数信息
     */
    private void buildTemplateManager(String pageName, String modelTypes[], String FormNames[]) {
        BaseOsCache oscache = OsCacheOtherManager.getInstance()
                .getBaseOsCache("param_manager_data_", 60 * 60 * 24);
        Map<String, Object> paramVo = new HashMap<String, Object>();
        for (int k = 0; k < FormNames.length; k++) {
            //如果之前已经存在相关配置，则不需要生成。
            String pName = pageName;// 未来应该提到外面，当参数传过来。
            String formName = FormNames[k];
            String key = formName + "_" + pName;
            Object obj = oscache.get(key);
            if (ToolsUtil.isEmpty(obj)) {
                Map<String, String> pmMap = new HashMap<String, String>();
                paramVo.put("sysParamManager.modelTypes", modelTypes[k]);
                paramVo.put("sysParamManager.formName", formName);
                paramVo.put("sysParamManager.delStatus", "F");
                paramVo.put("sysParamManager.createTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
                paramVo.put("sysParamManager.pageName", pageName);
                paramVo.put("modelTypes", "i_sysParamManager");
                initSave(paramVo);
            }
        }
        CreateParamManagerInfoJob.getInstance().initParamManagerInfo();
    }

    /**
     * description:  将类属性改成数据字段名,去前缀
     */
    protected String upperCharToUnderLine(String param) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || param.equals("")) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {
            builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
            i++;
        }
        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        String result = builder.toString();

        return result.substring(result.indexOf("_") + 1);
    }

    /**
     * 属性值生成,符合骆驼命名
     */
    protected String toCamelNamed(String str) {
        String names[] = str.split("_");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < names.length; i++) {
            if (i == 0) {
                sb.append(names[i].toLowerCase());
            } else {
                sb.append(names[i].substring(0, 1).toUpperCase() + names[i].substring(1)
                        .toLowerCase());
            }
        }
        return sb.toString();
    }

    /**
     * description:  将类属性改成数据字段名
     * type：true--去前缀  false--不去前缀
     */
    protected String upperCharToUnderLine(String param, boolean type) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || param.equals("")) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {
            builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
            i++;
        }
        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        String result = builder.toString();

        if (type) {
            result = result.substring(result.indexOf("_") + 1);
        }
        return result;

    }
}
